//
//  WYCHomeController.m
//  WYCweibo
//
//  Created by 魏云超 on 15/11/10.
//  Copyright (c) 2015年 魏云超. All rights reserved.
//

#import "WYCHomeController.h"
#import "WYCScanController.h"
#import "WYCTitleButton.h"
#import <AFNetworking/AFNetworking.h>
#import "WYCAccount.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "WYCStatus.h"
#import "WYCUser.h"
#import "WYCPhoto.h"
#import <MJExtension/MJExtension.h>
#import "WYCTableCell.h"
@interface WYCHomeController ()
@property (nonatomic, weak) WYCTitleButton *titleBtn;

//存储所有微博数据
@property (nonatomic, strong) NSArray *statuses;
//缓存cell高度 线程安全 内存紧张会自动释放 不会拷贝key
@property (nonatomic, strong) NSCache *rowHeightCache;
@end
//UIWindow *_window;
@implementation WYCHomeController



- (void)viewDidLoad {
    [super viewDidLoad];
    //设置左右按钮 中间弹框等
    [self setBtnAllUp];
    
    //设置未登录图片
    if (self.defaultCenterView) {
        self.defaultCenterView.infoContent = @"赶快登陆,精彩无限,一切皆有可能";
        self.defaultCenterView.iconName = @"visitordiscover_feed_image_house";
        self.defaultCenterView.show = YES;
    }else{
        //获取用户信息
        [self userInfo];
        //获取微博数据
        [self loadUpStatus];
    }
   }
//获取微博数据
-(void)loadUpStatus
{
    //1.封装请求参数
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"access_token"] = [WYCAccount accountFromSandbox].access_token;
//    dict[@"count"] = @(5);
    //2.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.发送请求
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
         //取出微博数据
        //self.statuses = responseObject[@"statuses"];
        NSArray *dicts = responseObject[@"statuses"];
        self.statuses = [WYCStatus mj_objectArrayWithKeyValuesArray:dicts];
        
//        for (WYCStatus *temp in self.statuses) {
//            WYCStatus *tt = temp;
//            NSLog(@"%@",tt);
//            NSLog(@"---------------------------------");
//        }
        //刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"获取微博数据失败"];
    }];
}
 //获取用户信息
-(void)userInfo
{
    //1.封装请求参数
    
    //2.获取管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //3.发送请求
    /*
     access_token	false	string	采用OAuth授权方式为必填参数，
     uid	false	int64	需要查询的用户ID。
     */
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    WYCAccount *account = [WYCAccount accountFromSandbox];
    dict[@"access_token"] = account.access_token;
    dict[@"uid"] = account.uid;
    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        DDLogInfo(@"%@",responseObject);
        //判断用户头像是否已经更新
        NSString *new = responseObject[@"profile_image_url"];
        if ([account.profile_image_url isEqualToString:new]) {
            return ;
        }else{
            account.profile_image_url = responseObject[@"profile_image_url"];
            [account save];
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showWithStatus:@"获取用户信息失败"];
    }];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.defaultCenterView!=nil) {
        //开始旋转
        WYCDefaultCenterView *defVC = self.view;
        [defVC startRun];
        
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.defaultCenterView!=nil) {
        //停止旋转
        WYCDefaultCenterView *defVC = self.view;
        [defVC endRun];
    }


}
-(void)setBtnAllUp
{
    //设置左右按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTitle:@"" norImage:@"navigationbar_friendsearch" selImage:@"navigationbar_friendsearch_highlighted" target:self action:nil];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:@"" norImage:@"navigationbar_pop" selImage:@"navigationbar_pop_highlighted" target:self action:@selector(scan)];
    //添加标题按钮
    WYCTitleButton *btn = [[WYCTitleButton alloc]init];
    [btn setTitle:@"一个大帅哥  " forState:UIControlStateNormal];
    //设置正常状态图片
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    //设置选中状态图片
    [btn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    btn.adjustsImageWhenHighlighted = NO;
    [btn sizeToFit];
    
    //监听按钮点击
    [btn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = btn;
    self.titleBtn  = btn;
}

//按钮点击事件
-(void)titleBtnClick:(WYCTitleButton *)btn {
    btn.selected = !btn.selected;
    //弹出框
    
    [self showMenu];
//    UITableView *tb = [[UITableView alloc]init];
//    tb.size = CGSizeMake(200, 200);
//    [self popFrom:btn content:tb];
}
UIWindow *_window;
-(void)popFrom:(UIView *)fromView content:(UIView *)contentView{
    //1.创建window
    _window = [[UIWindow alloc]init];
    _window.frame = [UIScreen mainScreen].bounds;
    _window.windowLevel = MAXFLOAT;
    
    //2.创建蒙版
    UIButton *cover = [[UIButton alloc]init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    [_window addSubview:cover];
    
    //3.创建菜单
    UIImageView *menuView = [[UIImageView alloc]init];
    menuView.userInteractionEnabled = YES;
    menuView.image = [UIImage imageNamed:@"popover_background"];
    [menuView addSubview:contentView];
    [cover addSubview:menuView];
    //4.设置菜单的frame
    //4.1 设置内容的x y相当于间隙
    contentView.x = 10;
    contentView.y = 15;
    //4.2设置菜单frame
    CGFloat menuViewY =  64-10;
    CGFloat menuViewW =  CGRectGetMaxX(contentView.frame) + contentView.x;
    CGFloat menuViewH =  CGRectGetMaxY(contentView.frame) + contentView.y;
    CGFloat menuViewX = self.view.frame.size.width * 0.5 -menuViewW * 0.5;
    menuView.frame = CGRectMake(menuViewX, menuViewY, menuViewW, menuViewH);
    //5.显示菜单
    _window.hidden = NO;

}

-(void)showMenu{
    UITableView *tb = [[UITableView alloc]init];
    tb.size = CGSizeMake(200, 200);
    tb.x = 10;
    tb.y = 15;
    //创建菜单
    UIImageView *menuView = [[UIImageView alloc]init];
    menuView.userInteractionEnabled = YES;
    menuView.image = [UIImage imageNamed:@"popover_background"];
    
    //设置菜单位置frame
    CGFloat menuViewY =  64-10;
    CGFloat menuViewW =  CGRectGetMaxX(tb.frame) + tb.x;
    CGFloat menuViewH =  CGRectGetMaxY(tb.frame) + tb.y;
    CGFloat menuViewX = self.view.frame.size.width * 0.5 -menuViewW * 0.5;
    menuView.frame = CGRectMake(menuViewX, menuViewY, menuViewW, menuViewH);
    //添加内容到菜单中
    [menuView addSubview:tb];
    
    //创建蒙版
    UIButton *cover = [[UIButton alloc]init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    [cover addSubview:menuView];
    //将菜单添加到父控件上
    //    [self.navigationController.tabBarController.view addSubview:cover];
    //获取window
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:cover];
//    _window = [[UIWindow alloc]init];
//    _window.frame = [UIScreen mainScreen].bounds;
//    _window.hidden = NO;
//    _window.windowLevel = MAXFLOAT;
//    [_window addSubview:cover];
}
-(void)coverClick:(UIButton *)coverBtn{
     //_window = nil;
    [coverBtn removeFromSuperview];
    //NSLog(@"abc");
   
    self.titleBtn.selected = !self.titleBtn.selected;
}
//点击扫描二维码
-(void)scan{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"WYCScanController" bundle:nil];
    UIViewController *vc = sb.instantiateInitialViewController;
        
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.一共有几组
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.每组有多少行
//    DDLogInfo(@"%lu",(unsigned long)self.statuses.count);
    return self.statuses.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1.创建cell
    WYCTableCell *cell = [tableView dequeueReusableCellWithIdentifier:[WYCTableCell identifier]];
    
    //2.设置数据
//    WYCStatus *status = self.statuses[indexPath.row];
//    WYCUser *user = status.user;
//    cell.textLabel.text = user.name;
//    cell.detailTextLabel.text = status.created_at;
//    NSURL *url = [NSURL URLWithString:user.profile_image_url];
//    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"abc"]];
    //2.设置数据
    WYCStatus *status = self.statuses[indexPath.row];
    cell.status = status;
    //3.返回cell
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //1.取出对应行模型
    WYCStatus *status = self.statuses[indexPath.row];
    //1.0 先从缓存取出高度
    NSNumber *rowHeight = [self.rowHeightCache objectForKey:status.idstr];
    
    CGFloat cellHeight = [rowHeight doubleValue];
    if (rowHeight == nil) {
        //1.1取出对应行的cell
        WYCTableCell *cell = [tableView dequeueReusableCellWithIdentifier:[WYCTableCell identifier]];
        //2.获取高度
        cellHeight = [cell cellHeightWithStatus:status];
        //3.缓存每一行高度
        [self.rowHeightCache setObject:@(cellHeight) forKey:status.idstr];
    }

    return cellHeight;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}

#pragma mark - lazy
-(NSCache *)rowHeightCache
{
    if (!_rowHeightCache) {
        _rowHeightCache  =  [[NSCache alloc]init];
        
    }
    return _rowHeightCache;
}
@end













